package net.alteiar.ui;

import java.awt.Dimension;
import java.awt.Point;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class MovablePanel extends JPanel {
	private static final long serialVersionUID = 1L;

	private final JScrollPane scrollCarte;
	private final JPanel panel;

	public MovablePanel(JPanel panel) {
		this.panel = panel;
		scrollCarte = new JScrollPane(panel,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

		this.add(scrollCarte);
	}

	@Override
	public void setPreferredSize(Dimension preferredSize) {
		scrollCarte.setPreferredSize(preferredSize);
	}

	public void moveInside(int moveX, int moveY) {
		Point newViewPos = scrollCarte.getViewport().getViewPosition();
		newViewPos.translate(moveX, moveY);

		newViewPos.x = Math.max(0, newViewPos.x);
		newViewPos.y = Math.max(0, newViewPos.y);

		newViewPos.x = Math.min(panel.getWidth()
				- scrollCarte.getViewport().getWidth(), newViewPos.x);
		newViewPos.y = Math.min(panel.getHeight()
				- scrollCarte.getViewport().getHeight(), newViewPos.y);

		scrollCarte.getViewport().setViewPosition(newViewPos);
	}
}
